package com.example.enrollservice.controller;

import com.example.enrollservice.entity.enrollment;
import com.example.enrollservice.service.enrollmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/enroll")
public class enrollmentController {

    @Autowired
    private enrollmentService enrollmentService;

    @PostMapping(value = "/api/enrollments", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String createEnrollment(@RequestBody Map<String, Object> req) {
        try {
            Object userId = req.get("userId");
            Object courseId = req.get("courseId");
            
            int userIdInt = (int) userId;
            int courseIdInt = (int) courseId;
            
            // 检查是否已经选过该课程
            enrollment existingEnrollment = enrollmentService.getEnrollmentByUserAndCourse(userIdInt, courseIdInt);
            if (existingEnrollment != null) {
                // 根据现有选课状态返回不同的提示信息
                int status = existingEnrollment.getStatus();
                switch (status) {
                    case 0:
                        return "该课程您已经申请，正在等待审核";
                    case 1:
                        return "该课程您已经选择并已通过审核";
                    case 2:
                        return "该课程您之前申请被拒绝，无法重复选择";
                    case 3:
                        return "该课程您已经退课，无法重复选择";
                    default:
                        return "该课程您已经选择";
                }
            }
            
            // 创建新的选课记录
            enrollment enroll = new enrollment();
            enroll.setUser_id(userIdInt);
            enroll.setCourse_id(courseIdInt);
            
            // 设置默认状态为待审核 (0)
            enroll.setStatus(0);
            
            // 设置申请时间
            String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            enroll.setRequest_time(currentTime);
            
            // decided_by字段保持为null（表示还未决定）
            
            enrollmentService.save(enroll);
            return "ok";
        } catch (Exception e) {
            e.printStackTrace();
            return "选课失败: " + e.getMessage();
        }
    }

    @GetMapping("/api/enrollments/student/{userId}")
    @ResponseBody
    public List<Map<String, Object>> getStudentEnrollments(@PathVariable int userId) {
        return enrollmentService.getStudentEnrollments(userId);
    }
    
    @GetMapping("/api/enrollments/user/{userId}")
    @ResponseBody
    public List<Map<String, Object>> getUserEnrollments(@PathVariable int userId) {
        return enrollmentService.getStudentEnrollments(userId);
    }
    
    @GetMapping("/api/enrollments/course/{courseId}")
    @ResponseBody
    public List<Map<String, Object>> getCourseEnrollments(@PathVariable int courseId) {
        return enrollmentService.getCourseEnrollments(courseId);
    }
    
    @PostMapping("/api/enrollments/approve")
    @ResponseBody
    public String approveEnrollment(@RequestBody Map<String, Object> requestBody) {
        return enrollmentService.approveEnrollment(requestBody);
    }
    
    @PostMapping("/api/enrollments/reject")
    @ResponseBody
    public String rejectEnrollment(@RequestBody Map<String, Object> requestBody) {
        return enrollmentService.rejectEnrollment(requestBody);
    }
}
